<template>
  <Wrapper>
    <el-button type="primary" @click="sendMsg">点我试一下</el-button>
  </Wrapper>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import logoImage from '@/assets/images/logo.png'

const router = useRouter()

function sendMsg() {
  sendNotification('标题', {
    body: '这是内容，点击跳转页面',
    data: {
      path: '/components/modal',
    },
    click(e) {
      console.log('点击了通知', e)
      if (!e || !Object.keys(e).length) return
      router.push(e.path)
    },
  })
}

async function sendNotification(title, options) {
  if (!('Notification' in window)) {
    return ElMessage.warning('该浏览器不支持此API')
  }

  const permission = Notification.permission
  if (permission === 'denied') {
    return ElMessage.error('已拒绝通知权限')
  }

  if (permission === 'granted') {
    console.log('已授予通知权限')
    notify(title, options)
  } else if (permission === 'default') {
    const [err, status] = await Notification.requestPermission()
      .then((status) => [null, status])
      .catch((err) => [err, null])
    return err || status === 'denied'
      ? Promise.reject()
      : notify(title, options)
  }

  function notify(title, options) {
    const notification = new Notification(title, {
      ...options,
      icon: logoImage,
    })

    notification.onclick = (e) => {
      notification.close()
      const { data } = e.target
      options.click && options.click(data)
    }

    notification.onclose = (e) => {
      ElMessage.success('关闭了通知')
      options.close && options.click(e)
    }
  }
}
</script>
